
public class IRCParser {
	
	private StringBuffer buf;
	private int len;
	private IRCCommand cmd;
	
	public IRCParser() {
		
	}
	
	public IRCCommand parse(String line) {
		cmd = new IRCCommand();
		buf = new StringBuffer(line);
		len = buf.length();
		int i = 0;
		
		i = removeWhitespaces(i);
		
		i = parsePrefix(i);
		
		i = removeWhitespaces(i);
		
		i = parseCommand(i);
		
		i = removeWhitespaces(i);
		
		// middle & trailing
		while(i < len && i != -1){
			i = parseParameter(i);
			i = removeWhitespaces(i);
		}
		
		return cmd;
	}
	
	private int parsePrefix(int i) {
		if(buf.charAt(i) == ':'){
			cmd.setPrefix(buf.substring(i+1, (i = indexOf(' ', i))));
		}
		return i;
	}
	
	private int parseCommand(int i) {
		if (Character.isDigit(buf.charAt(i))){
			cmd.setNumCommand(Integer.parseInt(buf.substring(i, ((i = indexOf(' ', i)) != -1) 
					? i : (i = len))));
		}
		else{
			cmd.setCommand(buf.substring(i, ((i = indexOf(' ', i)) != -1) 
					? i : (i = len)));
		}
		return i;
	}
	
	private int parseParameter(int i) {
		if(buf.charAt(i) == ':'){
			cmd.addParameter(buf.substring(i+1, (i = len)));
		}
		else {
			cmd.addParameter(buf.substring(i, ((i = indexOf(' ', i)) != -1) 
					? i : (i = len)));
		}
		return i;
	}
	
	private int indexOf(int c, int i) {
		while (i < len)
			if (buf.charAt(i++) == c)
				return --i;
		return -1;
	}
	
	private int removeWhitespaces(int i) {
		while(i < len && buf.charAt(i) == ' '){
			i++;
		}
		return i;
	}

}
